#!/usr/bin/env python
# -*- coding: utf-8 -*-

from sgmllib import SGMLParser
import urllib2,os,re
from datetime import datetime,timedelta


def __getHtmlSource( url,cookie=[] ):
    """ recupere le source html de l'url """
    import urllib
    txheaders = {   
        #~ "Host": "www.humanclock.com",
        "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3)Gecko/20040911 Firefox/0.10.1",
        "Accept": "image/png,*/*;q=0.5",
        "Accept-Language": "fr,en-us;q=0.7,en;q=0.3",
        "Accept-Encoding": "gzip,deflate",
        "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
        "Keep-Alive": "300",
        "Proxy-Connection": "keep-alive",
        'Cookie': ''.join(cookie)
    }

    r = urllib2.Request( url ,"",txheaders)
    return urllib2.urlopen(r).read()

class __getSpan(SGMLParser):
    def __init__(self,h):
        SGMLParser.__init__(self)
        self.feed(h)

    def reset(self):
        SGMLParser.reset(self)
        self.list = []
        self.buf=""
        
    def handle_data(self, text):
        self.buf+=text

    def start_span(self, attrs):
        self.buf=""
    def end_span(self):
        self.list.append(self.buf)

    def start_img(self, attrs):
        href = [v for k, v in attrs if k=='src']
        if href:
            self.list.append(os.path.basename(href[0]))


def getDays(dep):
    def __getCookie(url):
        """ return les cookies """
        u=urllib2.urlopen(url)
        cookie = u.info()['set-cookie']
        return cookie

    rep = os.path.dirname(__file__)
    rep="."
    
    recharge=True
    file = os.path.join(rep,"pc%d.html" % dep)
    if os.path.isfile(file):
        if datetime.fromtimestamp(os.stat(file).st_mtime) > datetime.today() - timedelta(hours=12):
            recharge=False
        
    if recharge:
        url="http://www.pleinchamp.com/meteo/meteoDept.aspx?dpt_id=%s&menu_id=35" % dep
        c=__getCookie(url)
        htmlSource = __getHtmlSource( url,c )
        open(file,"w").write(htmlSource)
    else:
        htmlSource = open(file,"r").read()

    days={}
    htmlSource = htmlSource.replace("table","µ")
    rr = re.compile("""<µ border="0" cellspacing="0" cellpadding="0" width="80" border="1" class="bottomRight">[^µ]+</µ>""",re.DOTALL|re.S)
    for i in rr.findall(htmlSource):
        p = __getSpan( i )
        jour =int( p.list[0].split(" ")[1] ) #num du jour
        img = p.list[2]
        min = p.list[4]# and int(p.list[4]) or None
        max = p.list[5]# and int(p.list[5]) or None
        
        days[jour] = (img,min,max)

    jours={}
    j = datetime.now()
    j -= timedelta(1) # hier
    for i in range(10):
        if j.day in days:
            jours[j.date()] = days[j.day]
            
        j += timedelta(1) # lendemain
    
    return jours
################################################################################
if __name__=="__main__":
    print getDays(67)
